package com.ruoyi.web.controller.Api;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.enums.Constant;
import com.ruoyi.common.utils.StringUtils;

import java.io.*;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.config.ThreadExecutorPoolConfig;
import com.ruoyi.system.V2.financial.mapper.FinanceMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.gameAttr.service.IGameAttrTemplateService;
import com.ruoyi.system.V2.gameAttr.service.IGameAttributeService;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoMapper;
import com.ruoyi.system.V2.inter.mapper.*;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.outto.service.IOutApi;
import com.ruoyi.system.phone.service.ITelManageNewService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("open/api/pzz")
public class OpenApiPZZController {

    @Autowired
    private IGameAttributeService gameAttributeService;
    @Autowired
    private IGameAttrTemplateService gameAttrTemplateService;
    @Resource
    private GoodsInfoMapper goodsInfoMapper;
    @Resource
    private ApiTaskPoolMapper apiTaskPoolMapper;
    @Autowired
    private IOutApi iOutApi;
    @Autowired
    private GameAttributeMapper gameAttributeMapper;

    @GetMapping("/demo")
    public void demo (){
        List<GameAttrTemplate> list = gameAttrTemplateService.yuduAttr(5L,"1");
        System.out.println(1111);
    }

    /**
     * 全量导入
     * @return
     */
    @GetMapping("/saveGameInfoAll")
    public AjaxResult saveGameInfoAll() {
        String str = getFile();
        String jsonObject = JSONObject.parseObject(str).getString("data");
        List<GameAttribute> list = JSONObject.parseArray(jsonObject, GameAttribute.class);
        for (GameAttribute attribute : list) {
            attribute.setId(null);
            gameAttributeMapper.insertGameAttribute(attribute);
            String acode = String.valueOf(attribute.getId());
            attribute.setAcode(acode);
            attribute.setParentId(0l);
            gameAttributeMapper.updateGameAttribute(attribute);
            if (!CollectionUtils.isEmpty(attribute.getChildGameAttributes())) {
                for (GameAttribute attribute1 : attribute.getChildGameAttributes()) {
                    attribute1.setId(null);
                    attribute1.setParentId(attribute.getId());
                    gameAttributeMapper.insertGameAttribute(attribute1);
                    if (!CollectionUtils.isEmpty(attribute1.getChildGameAttributes())) {
                        for (GameAttribute attribute2 : attribute1.getChildGameAttributes()) {
                            attribute2.setId(null);
                            attribute2.setParentId(attribute1.getId());
                            gameAttributeMapper.insertGameAttribute(attribute2);
                            if (!CollectionUtils.isEmpty(attribute2.getChildGameAttributes())) {
                                for (GameAttribute attribute3 : attribute2.getChildGameAttributes()) {
                                    attribute3.setId(null);
                                    attribute3.setParentId(attribute2.getId());
                                    gameAttributeMapper.insertGameAttribute(attribute3);
                                }
                            }
                        }
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    @Autowired
    private ThreadExecutorPoolConfig threadExecutorPoolConfig;
    @GetMapping("/pushApiEdit")
    public AjaxResult pushApiEdit(@RequestParam Map<String, Object> params) {
        Long id = MapUtils.getLong(params, "id");
        Long config = MapUtils.getLong(params, "config");
        iOutApi.edit(id, config,null);
        return AjaxResult.success();
    }

    @GetMapping("/pushDelApi")
    public AjaxResult pushDelApi(@RequestParam Map<String, Object> params) {


        Long id = MapUtils.getLong(params, "id");
        Long config = MapUtils.getLong(params, "config");
        iOutApi.del(id, config,1,null);

//        ArtRec artRecreq = new ArtRec();
//        artRecreq.setConfig(config);
//        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
//
//        for (ArtRec artRec : artRecs) {
//            iOutApi.del(artRec.getAccountId(), config,0,null);
//        }
        return AjaxResult.success();
    }

    @GetMapping("/iOutApi/edit")
    public  void iOutApiEdit( ) {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());

        /**
         * 1、循环任务池信息
         * 2、调用接口任务，成功的，修改状态
         */
        ApiTaskPool apiTaskPool = new ApiTaskPool();
        apiTaskPool.setStatus(3l);
        apiTaskPool.setCountt(1);
        apiTaskPool.setSize(1l);
        apiTaskPool.setType("edit");
        apiTaskPool.setNotPartCode("JYM");


        List<ApiTaskPool> apiTaskPoolList = apiTaskPoolMapper.selectApiTaskPoolList(apiTaskPool);

        List<Callable<Object>> tasks = new ArrayList<>();

        for (ApiTaskPool taskPool : apiTaskPoolList) {
            tasks.add(() -> {
                String type = taskPool.getType();
                if (true) {
                    if (Constant.edit.equals(type)) {
                        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(taskPool.getAccountId());
                        if (Objects.nonNull(goodsInfo)) {

                            iOutApi.edit(taskPool.getAccountId(), Long.parseLong(taskPool.getConfig()), taskPool.getId());
                        } else {
                            taskPool.setStatus(0l);
                            apiTaskPoolMapper.updateApiTaskPool(taskPool);
                        }
                    }
                } else {
                    taskPool.setStatus(0l);
                    apiTaskPoolMapper.updateApiTaskPool(taskPool);
                }
                return null;
            });
        }
        try {
            threadExecutorPoolConfig.threadPoolTaskExecutor().invokeAll(tasks);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    public String getFile() {
        StringBuffer buffer = new StringBuffer();

        File file = new File("E:\\文档\\VSCode\\json.json");

        String encoding = "utf-8";
        try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
             BufferedReader bufferedReader = new BufferedReader(read)) {
            //判断文件是否存在
            if (file.isFile() && file.exists()) {
                String lineTxt;
                while ((lineTxt = bufferedReader.readLine()) != null) {
//                    log.info(lineTxt);
                    buffer.append(lineTxt);
                }
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String str = buffer.toString();

        return str;
    }
    //导入游戏属性
    @GetMapping("/saveGameInfo")
    public AjaxResult saveGameInfo() {
        String str = getFile();
        String jsonObject = JSONObject.parseObject(str).getString("data");
        List<GameAttribute> list = JSONObject.parseArray(jsonObject, GameAttribute.class);
        for (GameAttribute gameAttribute : list) {
            GameAttribute gameAttributeParent = new GameAttribute();
            // 父级类目
            if (true) {
                GameAttribute attribute = new GameAttribute();
                attribute.setGameId(gameAttribute.getGameId());
                attribute.setFieldName(gameAttribute.getFieldName());
                attribute.setParentId(0l);
                List<GameAttribute> attributes = gameAttributeService.selectGameAttributeList(attribute);
                if (CollectionUtils.isEmpty(attributes)) {
                    gameAttributeParent = gameAttribute;
                    gameAttributeParent.setId(null);
                    gameAttributeParent.setCreateTime(new Date());
                    gameAttributeService.insertGameAttribute(gameAttributeParent);
                } else {
                    gameAttributeParent = attributes.get(0);
                }
            }
            // 子级类目
            if (true) {
                List<GameAttribute> childGameAttributes = gameAttribute.getChildGameAttributes();
                GameAttribute attribute = new GameAttribute();
                attribute.setParentId(gameAttributeParent.getId());
                List<GameAttribute> attributes = gameAttributeService.selectGameAttributeList(attribute);

                Map<String, List<GameAttribute>> collectField = new HashMap<>();
                try {
                    collectField = attributes.stream().filter(s -> StringUtils.isNotEmpty(s.getFieldName())).collect(Collectors.groupingBy(s -> s.getFieldName().replace(" ", "")));
                } catch (Exception e) {
                }

                for (GameAttribute childGameAttribute : childGameAttributes) {

                    if (collectField.keySet().contains(childGameAttribute.getFieldName().replace(" ", ""))) {
                        GameAttribute attribute1 = collectField.get(childGameAttribute.getFieldName().replace(" ", "")).get(0);
                        if (StringUtils.equals(childGameAttribute.getFieldName(), attribute1.getFieldName())) {
                            //UPDATE
                            childGameAttribute.setId(attribute1.getId());
                            childGameAttribute.setFieldName(attribute1.getFieldName());
                            childGameAttribute.setImgUrl(attribute1.getImgUrl());
//                            gameAttributeService.updateGameAttribute(childGameAttribute);
                        }
                    } else {
                        //insert
                        GameAttribute gameAttr = childGameAttribute;
                        gameAttr.setId(null);
                        gameAttr.setCreateTime(new Date());
                        gameAttr.setParentId(gameAttributeParent.getId());
                        gameAttributeService.insertGameAttribute(gameAttr);
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    @GetMapping("/wzryData")
    public void wzryData() {
        StringBuffer buffer = new StringBuffer();

        File file = new File("D:\\文档\\json.json");

        String encoding = "utf-8";
        try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
             BufferedReader bufferedReader = new BufferedReader(read)) {
            //判断文件是否存在
            if (file.isFile() && file.exists()) {
                String lineTxt;
                while ((lineTxt = bufferedReader.readLine()) != null) {
//                    log.info(lineTxt);
                    buffer.append(lineTxt);
                }
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject result = new JSONObject();
        String str = buffer.toString();
        JSONObject data = JSONObject.parseObject(str);
        List<JSONObject> heroData = JSONObject.parseArray(data.getString("heroData"), JSONObject.class);

        List<String> heroNameList = heroData.stream().map(s -> s.getString("heroName")).collect(Collectors.toList());
        result.put("heroNameList", heroNameList);
        JSONObject heoSkinConf = data.getJSONObject("heoSkinConf");
        List<JSONObject> heoSkinConfList = new ArrayList<>();
        JSONObject param = new JSONObject();


        Integer skinIds[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26
                , 27, 28, 29, 30, 31, 32, 33,
                34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45};
        Integer rongyao[] = {1};
        Integer remen[] = {1, 3, 4, 17, 18, 20, 23, 24, 26, 30, 31, 32, 33, 34, 35, 41, 45, 43, 42};
        Integer xianding[] = {4, 7, 8, 9, 10, 11, 17, 18, 20, 21, 23, 24, 30, 31, 32, 35, 45};
        Integer chuanshuo[] = {2};
        Integer shishi[] = {3};
        Integer wushuang[] = {75};

        List<JSONObject> skinList = new ArrayList<>();
        List<JSONObject> remenList = new ArrayList<>();
        List<JSONObject> rongyaoList = new ArrayList<>();
        List<JSONObject> xiandingList = new ArrayList<>();
        List<JSONObject> chuanshuoList = new ArrayList<>();
        List<JSONObject> shishiList = new ArrayList<>();
        List<JSONObject> wushuangList = new ArrayList<>();

        for (String key : heoSkinConf.keySet()) {
            String list = heoSkinConf.getJSONObject(key).getString("list");
            List<JSONObject> array = JSONObject.parseArray(list, JSONObject.class);
            for (JSONObject jsonObject : array) {
                param = new JSONObject();
                param.put("name", jsonObject.getString("heroName") + "-" + jsonObject.getString("skinName"));
                param.put("heroName", jsonObject.getString("heroName"));
                param.put("skinName", jsonObject.getString("skinName"));
                param.put("imgUrl", jsonObject.getString("imgUrl"));
                param.put("classType", jsonObject.get("classType"));
                List<Integer> classType = new ArrayList<>();
                if (StringUtils.isNotEmpty(jsonObject.getString("classType"))) {
                    classType = JSONObject.parseArray(jsonObject.getString("classType"), Integer.class);
                }
                param.put("classTypeName", jsonObject.get("classTypeName"));
                param.put("skinId", jsonObject.get("skinId"));
                heoSkinConfList.add(param);
                for (Integer local : classType) {
                    if (Arrays.asList(rongyao).contains(local)) {
                        rongyaoList.add(param);
                        break;
                    }
                    if (Arrays.asList(xianding).contains(local)) {
                        xiandingList.add(param);
                        break;
                    }
                    if (Arrays.asList(chuanshuo).contains(local)) {
                        chuanshuoList.add(param);
                        break;
                    }
                    if (Arrays.asList(shishi).contains(local)) {
                        shishiList.add(param);
                        break;
                    }
                    if (Arrays.asList(wushuang).contains(local)) {
                        wushuangList.add(param);
                        break;
                    }
                    if (Arrays.asList(remen).contains(local)) {
                        remenList.add(param);
                        break;
                    }
                }
            }
        }
        heoSkinConfList.sort(Comparator.comparing(s -> s.getString("skinId")));
        result.put("heoSkinConfList", heoSkinConfList);
        System.out.println(JSONObject.toJSONString(result));

        List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateService.selectGameAttrTemplateByGameId(2l);
        HashMap<String, List<JSONObject>> otherMap = new HashMap<>();
        otherMap.put("热门皮肤", remenList);
        otherMap.put("典藏皮肤", rongyaoList);
//        otherMap.put("星元皮肤",xiandingList);
        otherMap.put("传说皮肤", chuanshuoList);
        otherMap.put("史诗皮肤", shishiList);
        otherMap.put("无双", wushuangList);

        for (GameAttrTemplate gameAttrTemplate : gameAttrTemplates) {
            for (String key : otherMap.keySet()) {
                if (StringUtils.equals(gameAttrTemplate.getFieldName(), key)) {
                    List<JSONObject> valueList = otherMap.get(key);
                    GameAttribute attribute = new GameAttribute();
                    attribute.setParentId(gameAttrTemplate.getAttributeId());
                    List<GameAttribute> list = gameAttributeService.selectGameAttributeList(attribute);
                    List<String> collect = list.stream().map(s -> s.getFieldName()).collect(Collectors.toList());
                    for (JSONObject jsonObject : valueList) {
                        if (collect.contains(jsonObject.getString("name"))) {
                            continue;
                        }
                        GameAttribute gameAttribute = new GameAttribute();
                        gameAttribute.setGameId(2L);
                        gameAttribute.setGameName("王者荣耀");
                        gameAttribute.setParentId(gameAttrTemplate.getAttributeId());
                        gameAttribute.setFieldName(jsonObject.getString("name"));
                        gameAttribute.setImgUrl(jsonObject.getString("imgUrl"));
                        gameAttributeService.insertGameAttribute(gameAttribute);
                    }
                }
            }
        }
    }

    @GetMapping("/wuweiqiyue")
    public void wuweiqiyue() {
        StringBuffer buffer = new StringBuffer();

        File file = new File("D:\\文档\\json.json");

        String encoding = "utf-8";
        try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
             BufferedReader bufferedReader = new BufferedReader(read)) {
            //判断文件是否存在
            if (file.isFile() && file.exists()) {
                String lineTxt;
                while ((lineTxt = bufferedReader.readLine()) != null) {
//                    log.info(lineTxt);
                    buffer.append(lineTxt);
                }
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String str = buffer.toString();
        List<JSONObject> bundle_list = JSONObject.parseArray(JSONObject.parseObject(str).getJSONObject("data").getString("bundle_list"), JSONObject.class);
        JSONObject keyJson = new JSONObject();

        for (JSONObject tz : bundle_list) {
            JSONObject value = new JSONObject();
            value.put("bundle_id", tz.getString("bundle_id"));
            value.put("name", tz.getString("name"));
            value.put("icon", tz.getString("icon"));

            List<JSONObject> skin_list = JSONObject.parseArray(tz.getString("skin_list"), JSONObject.class);
            for (JSONObject skin : skin_list) {
                JSONObject val = new JSONObject();
                val.put("id", skin.getString("id"));
                val.put("name", skin.getString("name"));
                val.put("icon", skin.getString("icon"));
                val.put("gun_name", skin.getString("gun_name"));

                if (Objects.isNull(keyJson.get(skin.getString("gun_name")))) {
                    keyJson.put(skin.getString("gun_name"), Arrays.asList(val));
                } else {
                    List<JSONObject> array = JSONObject.parseArray(keyJson.getString(skin.getString("gun_name")), JSONObject.class);
                    array.add(val);
                    keyJson.put(skin.getString("gun_name"), array);
                }
            }

            if (Objects.isNull(keyJson.get("套装"))) {
                keyJson.put("套装", Arrays.asList(value));
            } else {
                List<JSONObject> array = JSONObject.parseArray(keyJson.getString("套装"), JSONObject.class);
                array.add(value);
                keyJson.put("套装", array);
            }
        }
        System.out.println(JSONObject.toJSONString(keyJson));

        GameAttrTemplate template = new GameAttrTemplate();
        template.setGameName("无畏契约");
        template.setFieldType("checkbox");
        List<GameAttrTemplate> attrTemplates = gameAttrTemplateService.selectGameAttrTemplateList(template);
        for (GameAttrTemplate attrTemplate : attrTemplates) {
            for (String s : keyJson.keySet()) {
                if (attrTemplate.getFieldName().contains(s)) {
                    GameAttribute ga = new GameAttribute();
                    ga.setParentId(attrTemplate.getAttributeId());
                    List<GameAttribute> list = gameAttributeService.selectGameAttributeList(ga);
                    List<JSONObject> valuesList = JSONObject.parseArray(keyJson.getString(s), JSONObject.class);
                    for (JSONObject json : valuesList) {
                        Boolean flag = false;
                        GameAttribute attr = new GameAttribute();
                        for (GameAttribute attribute : list) {
                            if (StringUtils.equals(attribute.getFieldName(), json.getString("name"))) {
                                attr = attribute;
                                flag = true;
                                break;
                            }
                            if (StringUtils.equals(attribute.getSid(), json.getString("id"))) {
                                attr = attribute;
                                flag = true;
                                break;
                            }
                        }
                        System.out.println(json.getString("name"));
                        // 新增
                        if (!flag) {
                            attr.setGameId(attrTemplate.getGameId());
                            attr.setGameName(attrTemplate.getGameName());
                            attr.setFieldName(json.getString("name"));
                            attr.setImgUrl(json.getString("icon"));
                            attr.setParentId(attrTemplate.getAttributeId());
                            attr.setSid(json.getString("id"));
                            gameAttributeService.insertGameAttribute(attr);
                        } else {
                            attr.setFieldName(json.getString("name"));
                            attr.setSid(json.getString("id"));
                            attr.setImgUrl(json.getString("icon"));
                            gameAttributeService.updateGameAttribute(attr);
                            // 更新
                        }
                    }


                }
            }
        }
    }
}